package com.jrh.web.apply;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jrh.dal.ApplyDao;
import com.jrh.dal.LabelDao;
import com.jrh.dal.UserProfileDao;
import com.jrh.domain.common.Page;
import com.jrh.domain.entity.Apply;
import com.jrh.domain.entity.Label;
import com.jrh.domain.entity.UserProfile;
import com.jrh.domain.user.LoginUserInfo;
import com.jrh.web.member.tools.UserAuthUtil;

/**
 * 前台申请的controller
 * 
 * @author yout 2012-8-12 下午2:31:14
 */
@Controller
@RequestMapping("/apply/")
public class ApplyController {

    private static final Integer pageSize = 6;

    @Autowired
    private ApplyDao             applyDao;

    @Autowired
    private UserProfileDao       userProfileDao;

    @Autowired
    private LabelDao             labelDao;

    @RequestMapping("list")
    public String list(Integer pageIndex, Model model, HttpServletRequest request, HttpServletResponse response) {
        LoginUserInfo userInfo = UserAuthUtil.getUserInfo(request, response);
        if (pageIndex == null) {
            pageIndex = 1;
        }
        Integer start = (pageIndex - 1) * pageSize;
        Apply apply = new Apply();
        apply.setUserId(userInfo.getUserId());
        Page<Apply> list = applyDao.list(apply, start, pageSize);
        model.addAttribute("list", list);
        return "/apply/list";
    }

    @RequestMapping(value = "apply", method = RequestMethod.GET)
    public String applyView(Model model, HttpServletRequest request, HttpServletResponse response) {
        LoginUserInfo userInfo = UserAuthUtil.getUserInfo(request, response);
        UserProfile userProfile = userProfileDao.getUserProfileByUserId(userInfo.getUserId());
        List<Label> styles = labelDao.listChildLabel(Label.LABEL_STYLE_KEY);
        model.addAttribute("styles", styles);
        model.addAttribute("user", userProfile);
        return "/apply/index";
    }

    @RequestMapping(value = "apply", method = RequestMethod.POST)
    @ResponseBody
    public String apply(Apply apply, Model model, HttpServletRequest request, HttpServletResponse response) {
        LoginUserInfo userInfo = UserAuthUtil.getUserInfo(request, response);
        apply.setUserId(userInfo.getUserId());
        applyDao.create(apply);
        return Boolean.TRUE.toString();
    }
}
